/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.mongo.connection.internal;

import com.mongodb.Mongo;
import com.mongodb.ReadPreference;
import lombok.Getter;
import org.jrose.api.annotation.persistence.MongoEntity;
import org.jrose.core.mongo.connection.DatabaseNameDecorator;
import org.jrose.core.mongo.connection.MongoConnectionHolder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

public class MongoConnectionHolderImpl implements MongoConnectionHolder, DisposableBean {
    @Getter private final Mongo mongo;
    @Getter private MongoDbFactory mongoDbFactory;
    @Getter private MongoTemplate mongoTemplate;

    public MongoConnectionHolderImpl(Mongo mongo,
                                     MongoEntity mongoEntity,
                                     DatabaseNameDecorator decorator,
                                     ApplicationContext applicationContext) {
        this.mongo = mongo;

        String databaseName = mongoEntity.database();
        if (decorator != null) {
            databaseName = decorator.decorate(databaseName);
        }

        mongoDbFactory = new SimpleMongoDbFactory(mongo, databaseName);

        MongoMappingContext mongoMappingContext = new MongoMappingContext();
        if (applicationContext != null) {
            mongoMappingContext.setApplicationContext(applicationContext);
        }

        MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory, mongoMappingContext);
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        if (applicationContext != null) {
            converter.setApplicationContext(applicationContext);
        }
        converter.afterPropertiesSet();

        mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
        if (applicationContext != null) {
            mongoTemplate.setApplicationContext(applicationContext);
        }
        switch (mongoEntity.readPreference()) {
            case PRIMARY: {
                mongoTemplate.setReadPreference(ReadPreference.primaryPreferred());
                break;
            }
            case SECONDARY: {
                mongoTemplate.setReadPreference(ReadPreference.secondaryPreferred());
                break;
            }
            default: {
                // do nothing
            }
        }
    }

    @Override
    public void close() throws Exception {
        if (mongoDbFactory != null && mongoDbFactory instanceof DisposableBean) {
            ((DisposableBean) mongoDbFactory).destroy();
        }
    }

    @Override
    public void destroy() throws Exception {
        close();
    }
}
